package org.dfl.core.model.transitions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.dfl.core.data.types.Type;
import org.dfl.core.data.types.TypeManager;
import org.dfl.core.model.TransitionExecutionException;
import org.dfl.messages.Messages;

/**
 * transition that union input collections
 * @author Piotr Wlodarczyk
 *
 */
public class UnionTransition extends MultipleInputsTransition {
	@Override
	protected int getDefaultMaxInputs() {
		return -1;
	}

	@Override
	protected int getDefaultMinInputs() {
		return 2;
	}
	
	@Override
	protected Type getDefaultOutputDefinition() {
		return TypeManager.getCollectionType();
	}
	
	@Override
	public void addInputDefinition(String key, Type type) throws Exception  {
		super.addInputDefinition(key, type);
		if(!getOutputTypeContainer().connectWith(getInputsDefinition().get(key))){
			getInputsDefinition().remove(key);
			throw new Exception(Messages.UnionTransition_errorInputSetsType);
		}
	}
	
	@Override
	protected void autoAddInputDefiniton(String key) throws Exception {
		addInputDefinition(key, TypeManager.getCollectionType());
	}
	
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	@Override
	protected Object fire(Map<String, Object> inputMap) throws TransitionExecutionException {
		ArrayList res = new ArrayList();
		Set<String> keys = inputMap.keySet();
		for(String key : keys){
			res.addAll((Collection) inputMap.get(key));
		}
		return res;
	}

	@Override
	public String getDefaultDescription() {
		return Messages.UnionTransition_description;
	}

}
